#include "implementations/RenderSystem.h"
#include "implementations/KeyManager.h"

vnav::graphics::_data_struct_* vnav::graphics::RenderSystem::m_data = 0;

void vnav::graphics::RenderSystem::initialize(VNInt width, VNInt height, VNBool fullscreen)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	m_data = new _data_struct_;
	m_data->windowClosed = false;

	if (fullscreen)
	{
		m_data->screen = SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE | SDL_OPENGL | SDL_FULLSCREEN);
	}
	else
	{
		m_data->screen = SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE | SDL_OPENGL);
	}

	glClearColor(0.0f, 0.0f, 0.0f, 1.0);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45, (VNFloat)width/height, 1.0, 500.0);
	glMatrixMode(GL_MODELVIEW);
	glEnable(GL_DEPTH_TEST);
}

void vnav::graphics::RenderSystem::beginFrame()
{
	m_data->time = SDL_GetTicks();
	while (SDL_PollEvent(&m_data->evt))
	{
		switch(m_data->evt.type)
		{
		case SDL_QUIT:
			m_data->windowClosed = true;
			break;
		case SDL_KEYDOWN:
			vnav::graphics::KeyManager::instance()->keyPressed(m_data->evt.key.keysym.sym);
			break;
		case SDL_KEYUP:
			vnav::graphics::KeyManager::instance()->keyReleased(m_data->evt.key.keysym.sym);
			break;
		}
	}
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
}

void vnav::graphics::RenderSystem::endFrame()
{
	SDL_GL_SwapBuffers();
	if (1000/30 > (SDL_GetTicks() - m_data->time))
		SDL_Delay (1000/30 - (SDL_GetTicks() - m_data->time));
}

void vnav::graphics::RenderSystem::finalize()
{
	SDL_Quit();
}

bool vnav::graphics::RenderSystem::isWindowClosed()
{
	return m_data->windowClosed;
}